# !/bin/bash
set -e

cd $( dirname ${BASH_SOURCE[0]} )
VERSION=$(sed -n 's/^\s*version\s*=\s*\(.*\)\s*/\1/p' .release)
IMAGE="repchain_block_courier:${VERSION}"

cd ../..
use_localhost=$(sed -n 's/\(.*\:\/\/\)\(localhost\)\(.*\)/\2/p' config/default.js) 

STATUS_PORT=$(sed -n 's/^\s*statusPort\s*:\s*\([0-9]*\)\s*,/\1/p' config/default.js)
if [ -z "${STATUS_PORT}" ]; then STATUS_PORT=8008; fi

CONTAINER_NAME="courier_repchain-block-courier"

docker run \
-v /var/run/docker.sock:/var/run/docker.sock \
-v ${PWD}/config:/usr/app/repchain-block-courier/config \
-v ${PWD}/logs:/usr/app/repchain-block-courier/logs \
-p ${STATUS_PORT}:8008 \
-d --name "${CONTAINER_NAME}" \
${IMAGE} bash -c \
"export HOST_NAME=\$(ip route show | awk '/default/{print \$3}') \
&& sed -i \"s/\(.*\:\/\/\)\(localhost\)\(.*\)/\1\${HOST_NAME}\3/\" config/default.js \
&& export echo \$(npx babel-node ./scripts/setup.js getEnvUrls) \
&& yarn deploy && cd database && npx prisma1 generate && yarn start"

cd scripts/docker 
echo "Waiting the application to be working"
# use wait-for-it from https://github.com/vishnubob/wait-for-it
./wait-for-it.sh -t 0 localhost:${STATUS_PORT} -- echo 'repchain-block-courier is up'

cd ../..
HOST_NAME=$(docker exec "${CONTAINER_NAME}" sh -c "ip route show | awk '/default/{print \$3}'")
# convert the docker0 ip to localhost in the configuration file
if [ ! -z "${use_localhost}" ]
then
sed -ri "s/(.*\:\/\/)(${HOST_NAME})(.*)/\1localhost\3/" config/default.js
fi

echo "OK"